package com.es.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.es.api.SystemResult;
import com.es.api.enums.GlobalEnableEnum;
import com.es.api.exception.OACSException;
import com.es.system.domain.SysRole;
import com.es.system.entity.SysRoleDO;
import com.es.system.mapper.SysRoleMapper;
import com.es.system.service.SysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author everysucceed
 * @since 2021-12-10
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRoleDO> implements SysRoleService {

    @Override
    public SystemResult<List<SysRole>> page(Integer page, Integer limit, SysRole sysRole) {
        Page<SysRoleDO> iPage = new Page<>(page, limit);
        iPage = baseMapper.selectPage(iPage, genWrapper(sysRole));
        List<SysRoleDO> list = iPage.getRecords();
        if(list!=null && !list.isEmpty()){
            List<SysRole> data = new ArrayList<>();
            list.forEach(e->{
                SysRole v = new SysRole();
                BeanUtils.copyProperties(e, v);
                v.setDataEnableTitle(GlobalEnableEnum.getTitleByCode(e.getDataEnable()));
                data.add(v);
            });
            SystemResult result = SystemResult.success(data);
            result.setCount(iPage.getTotal());
            return result;
        }
        return SystemResult.empty("暂无数据");
    }

    @Override
    public SystemResult<Serializable> save(SysRole sysRole) throws OACSException {
        if(sysRole == null){
            throw new OACSException("系统角色不能为空");
        }
        SysRoleDO sysRoleDO = new SysRoleDO();
        BeanUtils.copyProperties(sysRole,sysRoleDO);
        sysRoleDO.setCreateTime(LocalDateTime.now());
        sysRoleDO.setUpdateTime(LocalDateTime.now());
        sysRoleDO.setDataEnable(0);
        baseMapper.insert(sysRoleDO);
        return SystemResult.success(sysRoleDO.getDataId());
    }

    /**
     * @param sysRole 生成动态sql
     * @return
     */
    private LambdaQueryWrapper<SysRoleDO> genWrapper(SysRole sysRole) {
        if(sysRole == null){
            return  null;
        }
        LambdaQueryWrapper<SysRoleDO> wrapper =  Wrappers.lambdaQuery(SysRoleDO.class);
        if(sysRole.getDataId()!=null){
            wrapper.eq(SysRoleDO::getDataId, sysRole.getDataId());
        }
        return wrapper;
    }
}
